package pattern

import (
  "github.com/akirakazu/go-simplejson"
)

// Match pattern with msg
func Match(pattern, msg *json.Json) bool {
	m, err := msg.Map()
	if err != nil {
		return false
	}

	arr, err := pattern.Array()
	if err == nil {
		for _, element := range arr {
			if patternMatch(element, m) {
				return true
			}
		}
	} else {
		p, err := pattern.Map()
		if err != nil {
			return false
		}
		if patternMatch(p, m) {
			return true
		}
	}
	return false
}

func patternMatch(pattern, msg interface{}) bool {
	_p := pattern.(map[string]interface{})
	_m := msg.(map[string]interface{})
	for k, v := range _p {
		_pv, ok := _m[k]
		if !ok {
			return false
		}
		if _, vok := v.(map[string]interface{}); vok {
			if _, pvok := _pv.(map[string]interface{}); !pvok {
				return false
			}
			if !patternMatch(v, _pv) {
				return false
			}
		} else {
			if _pv != v {
				return false
			}
		}
	}
	return true
}
